﻿using System;
using System.Threading.Tasks;
using Pay.Core;
using Pay.DTO.hxdata;
using Flurl.Http;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace Pay.Service {
	/// <summary>
	/// 汇享天成
	/// </summary>
	public class HxDataSign {
		public string ser_publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGpLwvfOKSHYrR0/9iWondVpTS2Ib8Uhh0IMzCIPlWGNur08aHoC/IdA8ZFJXo0phZ3mMkuk//PkrNajxEBWI/mXEsIXJNjvqjg5lC5q27QAGoPeFIafgV00QNJSnFF5s82wpS8ua/hiqhkVaDavGFxzGhfTzho7Rvab+nDCIjSwIDAQAB";
#if DEBUG
		protected string api_url = "http://api.mypays.cn/api/service.json";
		public string privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL2KZTnHXigg94BuqD1b5NnGhF2hkgWl/MA/EVDldgyjgybfnVmNqj+M2TpETOSGHq5AiiEif0Q+s9/5dY1WomLGRwmJDIAdIKC8Z9FkW3pJAYdNjfFNcr7CjXn/amq/9y7ajjAfTuF2B0eX7rOFzndGy8w0XBhLH981C8kWrzOzAgMBAAECgYA5wK6hUVcmQQ1JC+6la5eqp6tzYCS/JdmCtnTPQmua5EO1F5O5UsoaPQ9/ioonY5p7m9y6xekjYTurtjYUT96AVbD+XopnvX34GdWGcm0bo0Nt4geQZx6VcFQJtp0yNJnCkBBXELh7X3e7yVxaSGjhieqg36m3bjkaDZc9s7EekQJBAO0vOvz2qejTZRsokSW80C00MXS415iS1mK9FujU+fFAwOQxJ9GXQBiYT7yfZL3tRGlbvij1Doe9iqTQFzDqhzsCQQDMk5uHtCveNQjDXZRERCfG674AqHTB38kBU1Dc4fb7m7X5TOdEGGtN4bCg1ioedoZ0AUSqkQJaptlXvrxikm3pAkBftAsNP0pX09ScHMZUf9dQJhs+iccUnUs8FChGUol3uzUZ3mu+ulT2l5608Wvo5vAPwyD7zcXLJ8PltMFmz3s5AkBlqMg19FOEVYhoRP1juxalJArEGvICUal6LiPVz7hDKgqQuyWFUjkod4mlMye1AaMozGSJ+gtYbuc8Uj0dIrTZAkEA342TgScCl40Y+hhvaMC108sjlUMzoUGsE6Ai8hrc9uwIepk3BXFj4bYpThDkSKhe98YRJS+/ucJUwubFK4TU4Q==";
		//public string publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9imU5x14oIPeAbqg9W+TZxoRdoZIFpfzAPxFQ5XYMo4Mm351Zjao/jNk6REzkhh6uQIohIn9EPrPf+XWNVqJixkcJiQyAHSCgvGfRZFt6SQGHTY3xTXK+wo15/2pqv/cu2o4wH07hdgdHl+6zhc53RsvMNFwYSx/fNQvJFq8zswIDAQAB";
#else
		protected string api_url = "http://api.mypays.cn/api/service.json";
		public string privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK4kGhxWPH3stjBwstoLVDkPLFvTrNCWSkXJpH4xQbs1eitBE0u0R2xhB3mQ5TpSBdjb23/L8o8Obe6JUoMPwRwW6aUt08hpLesDc2B7asx+xX1IyexrIuWiY89gjCgGWJxDPfVPhow+NV9/Y9TJyJFwK3fOplHuFfXMZmZ7wwy1AgMBAAECgYAFc9PtdzXFq5e4xI6VDS3B65uz9FjA3zPMI5gm61vnhLEikZMNF8P0vMUDJWpH/TF5rMieo8Aggo8mnN4chG3DairxejldTff9D7JutzKgF4PUWut+a7O/8W5aZ6qxmpvWe21KEhsAiaX5GQ+Epz7WVAUn+Ixl2E2n/TLzGbAagQJBANapgAzGrnkbPA2hc4zNKnv+AyeryKJL9BwMgKVJ1QTPrICyF9qvfAE9IkApEIm7p/X1HmlBL3u10tj3X/+n/9kCQQDPrPoROhKJHMjy45bld0vpVraq3hjoAedlnjCJt++JlsXu/PT8cO646eyGg2kVMqRBY0M57xDktu4ycXutHAY9AkEAihAUiqMSvlO06TNpJSsj4wG5t7812KSvSYcFCsoU1vZXBaMF0qJBSG6wY8HFoEBww7G2sI27Y37LML7SIJVF6QJBAJW0gPOoJDJ48Ja+30j9DVjgrH9R6SxeKvuC5ERytpc9e+PCr6vGkR/1aQ6ybi7cubF1J8H8hvYItH7idaAdgpUCQENiGikTfWYseZo2rpis9nWLYytC7cLJGrabMpBApYQu3fTv2akrGwB8X5a5BjuN0qe4KJ09NeeJZZ3szWFG5Vw=";
		//public string publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGpLwvfOKSHYrR0/9iWondVpTS2Ib8Uhh0IMzCIPlWGNur08aHoC/IdA8ZFJXo0phZ3mMkuk//PkrNajxEBWI/mXEsIXJNjvqjg5lC5q27QAGoPeFIafgV00QNJSnFF5s82wpS8ua/hiqhkVaDavGFxzGhfTzho7Rvab+nDCIjSwIDAQAB";
#endif
#if DEBUG
		protected string app_id = "f6c61712b6854cfd903a63daf65371cd";
#else
		protected string app_id = "133135e8980a4d4fa4beece7490fc3be";
#endif

		/// <summary>
		/// HF银联请求通道封装
		/// </summary>
		/// <returns>The pay gateway.</returns>
		/// <param name="model">Model.</param>
		/// <typeparam name="T">The 1st type parameter.</typeparam>
		public async Task<hx_resp_base<T>> PayGateway<T>(hx_head_base model) where T : new() {
			model.sign = Sign(model);
			var log = IocHelper.Get<ILogHelper>("info");
			var json = model.ToJson();
			log.Info(json);
			try {
				var resp = await api_url.PostJsonAsync(model).ReceiveJson<hx_resp_base>();
				log.Info(resp.ToJson());
				var result = new hx_resp_base<T> {
					app_id = resp.app_id, client_trans_id = resp.client_trans_id, resp_code = resp.resp_code, resp_msg = resp.resp_msg,
					server_trans_id = resp.server_trans_id, sign = resp.sign, trans_timestamp = resp.trans_timestamp
				};
				result.data = resp.data.ToObject<T>();
				return result;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return null;
			}
		}

		public async Task<hx_resp_base> PayGateway2(hx_head_base model) {
			model.sign = Sign(model);
			var log = IocHelper.Get<ILogHelper>("info");
			var json = model.ToJson();
			log.Info(json);
			try {
				var resp = await api_url.PostJsonAsync(model).ReceiveJson<hx_resp_base>();
				return resp;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return null;
			}
		}

		/// <summary>
		/// HF银联请求通道封装sign.
		/// </summary>
		/// <returns>The sign.</returns>
		/// <param name="model">Model.</param>
		/// <typeparam name="T">The 1st type parameter.</typeparam>
		/// <typeparam name="V">The 2nd type parameter.</typeparam>
		public string Sign(hx_head_base model) {
			model.app_id = app_id;
			var result = _sign(model);
			result = RSAFromPkcs.sign2md5(result, privateKey, "utf-8");
			return result;
		}

		private string _sign(hx_head_base model) {
			string json = model.ToJson();
			var collection = json.ToObject<SortedDictionary<string, object>>();
			collection.Remove("sign");
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Value is JObject) {
					var obj = kv.Value as JObject;
					result += "&" + kv.Key + "=" + obj.ToJson();
				} else
					result += "&" + kv.Key + "=" + kv.Value;
			}
			result = result.Trim('&');
			//var log = IocHelper.Get<ILogHelper>("info");
			//log.Info(result);
			return result;
		}

		/// <summary>
		/// 异步通知验签
		/// </summary>
		public bool VerifySign(hx_notify_model model) {
			var sortJson = string.Format("client_trans_id={0}|resp_code={1}", model.client_trans_id, model.resp_code);
			var result = RSAFromPkcs.verify2md5(sortJson, model.sign, ser_publicKey, "utf-8");
			return result;
		}
	}
}
